<template>
  <!-- 外部头像 -->
  <div id="account-mode" @click="handleAccountDropdown">
    <el-avatar :size="60" v-if="loginStatusId">
      <img :src="matchedUser.img" alt="用户头像" class="avatar-img" />
    </el-avatar>
    <el-avatar :size="60" :icon="UserFilled" v-else></el-avatar>
  </div>
  <!-- 头像下拉框 -->
  <Transition>
    <div class="account-dropdown" v-show="accountDropdownId">
      <!-- ====================上半部分======================= -->
      <!-- 修改账户 -->
      <div class="set-account" v-if="loginStatusId">
        <div class="header">
          <!-- 修改：下拉框内头像也根据URL动态显示 -->
          <el-avatar :size="40" v-if="loginStatusId">
            <img :src="matchedUser.img" alt="用户头像" class="avatar-img" />
          </el-avatar>
          <el-avatar :size="40" :icon="UserFilled" v-else></el-avatar>
          <span>{{ matchedUser.name }}</span>
        </div>
        <i
          class="iconfont icon-bianji"
          @click="handlePushToAvatar(matchedUser.id)"
          title="修改账户"
        >
        </i>
      </div>
      <!-- 登录账户 -->
      <div class="login-account" v-else>
        <div class="login-account-left">
          <span>登录后可享受</span><br />
          <span>更多贴心服务</span>
        </div>
        <el-button
          class="login-account-right"
          type="primary"
          plain
          @click="handleLogin1"
          >登录</el-button
        >
      </div>
      <!-- =======================下半部分==================== -->
      <div class="bottom-container">
        <!-- 我的收藏 -->
        <div class="my-favorites">
          <i class="iconfont icon-wenjianjia"></i>
          <span>我的收藏</span>
        </div>
        <!-- 显隐收藏点 -->
        <div class="show-favorites">
          <div class="show-favorites-left">
            <i class="iconfont icon-shoucang"></i>
            <span>显示收藏点</span>
          </div>
          <el-form-item>
            <el-checkbox v-model="isShowFavorites"></el-checkbox>
          </el-form-item>
        </div>
        <!-- 图层切换 -->
        <div class="layers">
          <div class="layers-title">
            <i class="iconfont icon-tuceng"></i>
            <span>主题</span>
          </div>
          <div class="layers-list">
            <el-button>标准</el-button>
            <el-button>夜景</el-button>
          </div>
        </div>
        <!-- 退出登录 -->
        <div class="logout-account" v-show="logoutId" @click="handleLogout">
          <i class="iconfont icon-tuichu"></i>
          <span>退出登录</span>
        </div>
      </div>
    </div>
  </Transition>
  <!-- 登录面板 -->
  <Transition>
    <div class="login-container" v-show="loginPanelId">
      <div class="left-container">
        <img
          src="https://a.amap.com/lbs-p/static/banner/passport_left_banner_default.jpg"
        />
      </div>
      <div class="right-container">
        <div class="title">
          <span>账号登录</span>
          <i class="iconfont icon-chahao" @click="handleLogin1"> </i>
        </div>
        <el-input
          class="account"
          v-model="inputAccount"
          type="text"
          placeholder="请输入账号"
          clearable
          @focus="handle2request"
        />
        <el-input
          class="password"
          v-model="inputPassword"
          type="password"
          placeholder="请输入密码"
          show-password
        />
        <el-button
          class="OKlogin"
          type="primary"
          style="border-radius: 0px"
          @click="handleLogin2"
          >立即登录</el-button
        >
        <div class="declare">
          <el-form-item>
            <el-checkbox v-model="isAgree"></el-checkbox>
          </el-form-item>
          <span>
            我已阅读并同意
            <a href="#">《 高德服务条款 》</a>
            <a href="#">《 高德地图基本功能隐私政策 》</a>
            <a href="#">《 高德账号服务个人信息处理规则 》</a>; 仅用于学习！！！
          </span>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { UserFilled } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
// 导入获取用户信息的方法
import { getUser, getSingleUser } from '@/api/account.js';

// 跳转路由专业
const router = useRouter();

// 🐖存储请求的数据库用户信息
const user = ref([]);
// 存储匹配的用户信息
const matchedUser = ref([]);

// 控制显隐账户下拉框id
const accountDropdownId = ref(false);
// 存储头像URL
const avatarUrl = ref('');
// 收藏点显隐id
const isShowFavorites = ref(true);

// ⚠️登录状态id
const loginStatusId = ref(false);
// 登录面板显隐id
const loginPanelId = ref(false);
// 是否同意隐私协议
const isAgree = ref(true);
// 推出登入id
const logoutId = ref(false);

// 账号 实时输入的内容
const inputAccount = ref('');
// 密码 实时输入的内容
const inputPassword = ref('');

onMounted(async () => {
  //✅从本地存储中获取 登录状态 和 退出登入按钮，用户id
  const savedLoginStatusId = localStorage.getItem('loginStatusId');
  const savedLogoutId = localStorage.getItem('logoutId');
  const savedCurrentUserId = localStorage.getItem('currentUserId');
  console.log(savedCurrentUserId, '用户id');
  if (savedLoginStatusId && savedLogoutId) {
    loginStatusId.value = JSON.parse(savedLoginStatusId);
    logoutId.value = JSON.parse(savedLogoutId);
  }
  // 获取用户id，如果存在->重新请求 id用户（更新）
  if (savedCurrentUserId !== null && savedCurrentUserId) {
    try {
      // 获取用户信息
      user.value = await getSingleUser(savedCurrentUserId);
      console.log('获取id用户成功', user.value);
      // 更新匹配用户信息
      matchedUser.value = user.value;
    } catch (err) {
      console.log('请求id用户失败', err);
    }
  } else {
    // 初始登录 请求数据
    try {
      // 获取用户信息
      user.value = await getUser();
      console.log('请求数据库成功', user.value);
    } catch (err) {
      console.log('请求数据库失败', err);
    }
  }
});

// ===================显隐账户下拉框===============
const handleAccountDropdown = () => {
  accountDropdownId.value = !accountDropdownId.value;
};

// ====================登入账户-下拉框===================
const handleLogin1 = () => {
  // 显示登入面板
  loginPanelId.value = !loginPanelId.value;
  // 关闭账户下拉框
  accountDropdownId.value = false;
};

// ====================🐖二次登入重新请求数据===============
const handle2request = async () => {
  const savedCurrentUserId = localStorage.getItem('currentUserId');
  console.log(savedCurrentUserId, '22用户id');
  // 初始登入不请求数据
  if (savedCurrentUserId !== null) {
    return;
  } else if (savedCurrentUserId === null) {
    // 二次登入请求数据
    try {
      // 获取用户信息
      user.value = await getUser();
      console.log('22请求数据库成功', user.value);
    } catch (err) {
      console.log('22请求数据库失败', err);
    }
  }
};

// ====================登入账户-登入面板============
const handleLogin2 = () => {
  // 验证协议
  if (!isAgree.value) {
    alert('请阅读并同意协议');
    return;
  }

  // 验证账号密码
  // 关键：从用户列表中找到账号匹配的用户对象
  matchedUser.value = user.value.find(
    (item) => item.account === inputAccount.value
  );
  console.log('匹配的用户', matchedUser.value);
  if (inputAccount.value === '' || inputPassword.value === '') {
    alert('账号或密码不能为空！');
    return;
  } else if (!matchedUser.value) {
    alert('账号不存在,请注册登录！');
    return;
  } else if (
    matchedUser &&
    inputPassword.value !== matchedUser.value.password
  ) {
    alert('密码错误,请重新输入！');
    return;
  } else if (
    matchedUser &&
    inputPassword.value === matchedUser.value.password
  ) {
    alert('登录成功,欢迎！');
    // 清空输入框
    inputAccount.value = '';
    inputPassword.value = '';

    // 关闭 登入面板
    loginPanelId.value = !loginPanelId.value;
    // 修改为 登入状态
    loginStatusId.value = true;
    // 显示退出登入按钮
    logoutId.value = true;
    // ➕保存 登入状态和 退出登入按钮 ,id 到本地存储
    localStorage.setItem('loginStatusId', JSON.stringify(loginStatusId.value));
    localStorage.setItem('logoutId', JSON.stringify(logoutId.value));
    localStorage.setItem('currentUserId', matchedUser.value.id);
  }
};

// ====================退出登录=============
const handleLogout = () => {
  // 更改登入状态
  loginStatusId.value = false;
  // 隐藏推出登入按钮
  logoutId.value = false;
  // ➕保存 登入状态和 退出登入按钮 到本地存储
  localStorage.setItem('loginStatusId', JSON.stringify(loginStatusId.value));
  localStorage.setItem('logoutId', JSON.stringify(logoutId.value));
  // 移除存储的用户id
  localStorage.removeItem('currentUserId');
  console.log('用户id已清除');
  // 清空请求用户信息
  user.value = [];
};

// ====================跳转至修改账户页面================
const handlePushToAvatar = (id) => {
  router.push(`/SetAccount/${id}`);
};
</script>

<style lang="scss" scoped>
@import '//at.alicdn.com/t/c/font_4989585_wz6a68u9ziq.css';
// 动画
.v-enter-active {
  transition: all 0.3s ease-out; /* 淡入时间和缓动效果 */
}
.v-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1); /* 缩短移出时间至0.2s实现快速移出 */
}
.v-enter-from,
.v-leave-to {
  transform: translateY(20px); /* 将X轴变换改为Y轴变换，实现上下方向动画 */
  opacity: 0;
}

// 外部头像
#account-mode {
  position: absolute;
  top: 7px;
  right: 27px;
  .el-avatar--circle {
    border: 3px solid #ffffff;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  }
}
// 头像下拉框
.account-dropdown {
  position: absolute;
  top: 80px;
  right: 27px;
  width: 250px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  // 登入账户
  .login-account {
    background-color: #2c9eff;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    padding: 10px 0;
    span {
      font-size: 13px;
      color: #ffffff;
    }
    button {
      width: 80px;
      height: 30px;
    }
  }
  // 修改账户
  .set-account {
    background-color: #2c9eff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 15px;
    .header {
      display: flex;
      align-items: center;
      gap: 8px;
      .el-avatar--circle {
        border: 2px solid #ffffff;
      }
      span {
        font-size: 14px;
        color: #ffffff;
      }
    }
    .icon-bianji {
      color: #ffffff;
    }
  }
  .bottom-container {
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    gap: 18px;
    padding: 12px 20px;
    // 我的收藏
    .my-favorites {
      display: flex;
      align-items: center;
      gap: 7px;
      i {
        font-size: 16px;
        color: #7c8196;
      }
      span {
        font-size: 14px;
        color: #7c8196;
      }
    }
    // 显隐收藏点
    .show-favorites {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .show-favorites-left {
        display: flex;
        gap: 7px;
        i {
          font-size: 16px;
          color: #ffae00;
        }
        span {
          font-size: 14px;
          color: #7c8196;
        }
      }

      .el-form-item {
        margin-bottom: 0;
      }
    }
    // 切换图层
    .layers {
      .layers-title {
        display: flex;
        align-items: center;
        gap: 7px;
        i {
          font-size: 21px;
          color: #7c8196;
        }
        span {
          font-size: 14px;
          color: #7c8196;
        }
      }
      .layers-list {
        margin-top: 9px;
        button {
          height: 28px;
        }
      }
    }
    // 退出登录
    .logout-account {
      display: flex;
      align-items: center;
      gap: 7px;
      i {
        font-size: 16px;
        color: #7c8196;
      }
      span {
        font-size: 14px;
        color: #7c8196;
      }
    }
  }
}
// 登入面板
.login-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 850px;
  height: 450px;
  display: flex;
  .left-container {
    img {
      width: 330px;
      height: 100%;
    }
  }
  .right-container {
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    flex: 1;
    gap: 30px;
    padding: 30px 50px;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span {
        font-size: 30px;
      }
    }
    .el-input {
      height: 40px;
    }
    .OKlogin {
      height: 40px;
    }
    .declare {
      display: flex;
      gap: 10px;
      span {
        font-size: 14px;
        a {
          text-decoration: none;
          color: #2c9eff;
        }
      }
    }
  }
}
</style>
